package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.CodeRule;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //如果不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //符合，生成验证码
        String code = RandomUtil.randomNumbers(CodeRule.SIX_DIGIT_CODE.getCodeNums());
        //保存验证码到Session
        //session.setAttribute("code", code);
        //session.setMaxInactiveInterval(3600);//以秒为单位
        //保存验证码到Redis中，设置有效期为5分钟
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //发送验证码
        log.info("发送短信验证码成功，验证码为" + code);
        //返回成功结果
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验手机号(防止在发送验证码后更改了无效的手机号)
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        User user = null;
        //校验验证码
        if (StringUtils.hasLength(loginForm.getCode())) {
            //此时为验证码登录
            //Object cacheCode = session.getAttribute("code");
            String cacheCode = redisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
            if (cacheCode == null || !cacheCode.equals(loginForm.getCode())) {
                //验证码过期或不一致
                return Result.fail("验证码错误！");
            }
            //验证码正确，需要查询用户
            user = this.lambdaQuery().eq(User::getPhone, phone).one();
            //判断用户是否存在
            if (user == null) {
                //不存在则创建新用户，存入数据库中
                user = createWithPhone(phone);
            }
        } else {
            //此时为密码登录
            String password = loginForm.getPassword();
            if (!StringUtils.hasLength(password)) {
                return Result.fail("密码为空，请重新输入密码！");
            }
            //查询用户
            user = this.lambdaQuery().eq(User::getPhone, phone).one();
            //判断用户是否存在
            if (user == null) {
                return Result.fail("用户不存在，新用户请使用验证码方式登录！");
            }
            //校验密码
            if (!password.equals(user.getPassword())) {
                return Result.fail("密码错误！");
            }
        }
        //脱敏后保存用户信息到Session中
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        //session.setAttribute("user", userDTO);
        //生成token作为登录令牌
        String token = UUID.randomUUID().toString(true);
        //将userDTO转为Map对象
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //脱敏后保存用户信息到Redis中
        redisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY + token, userMap);
        //设置token有效期
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //返回token
        return Result.ok(token);
    }

    private User createWithPhone(String phone) {
        //创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        this.save(user);
        return user;
    }
}
